package net.wanho.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import net.wanho.dto.TransshipmentAddDTO;
import net.wanho.dto.TransshipmentConfirmDTO;
import net.wanho.dto.TransshipmentDTO;
import net.wanho.mapper.ProductMapper;
import net.wanho.mapper.TransshipmentMapper;
import net.wanho.po.Product;
import net.wanho.po.Transshipment;
import net.wanho.service.TransshipmentService;
import net.wanho.util.CurrentUtil;
import net.wanho.vo.PageInfo;
import net.wanho.vo.TransshipmentVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * @author 32033
 * @description 针对表【transshipment(调货单表)】的数据库操作Service实现
 * @createDate 2025-01-11 17:01:23
 */
@Service
@RequiredArgsConstructor
public class TransshipmentServiceImpl extends ServiceImpl<TransshipmentMapper, Transshipment>
        implements TransshipmentService {

    private final ProductMapper productMapper;

    @Override
    public PageInfo<TransshipmentVo> getPage(int pageNum, int pageSize, TransshipmentDTO transshipmentDTO) {
        Page<TransshipmentVo> page = new Page<>(pageNum, pageSize);
        QueryWrapper<TransshipmentVo> wrapper = new QueryWrapper<>();
        wrapper.eq(transshipmentDTO.getSourceStoreId() != null, "t.source_store_id", transshipmentDTO.getSourceStoreId())
                .eq(transshipmentDTO.getTargetStoreId() != null, "t.target_store_id", transshipmentDTO.getTargetStoreId())
                .like(StringUtils.hasText(transshipmentDTO.getSourceProductName()), "p.product_name", transshipmentDTO.getSourceProductName())
                .like(StringUtils.hasText(transshipmentDTO.getTargetProductName()), "pt.product_name", transshipmentDTO.getTargetProductName())
                .like(StringUtils.hasText(transshipmentDTO.getCreateName()), "ui.user_name", transshipmentDTO.getCreateName());

        Page<TransshipmentVo> pageResult = this.baseMapper.findPage(page, wrapper);

        PageInfo<TransshipmentVo> pageInfo = new PageInfo<>();
        pageInfo.setResultList(pageResult.getRecords());
        pageInfo.setPageCount(pageResult.getPages());
        pageInfo.setTotalNum(pageResult.getTotal());
        pageInfo.setPageSize(pageResult.getSize());
        pageInfo.setPageNum(pageResult.getCurrent());
        pageInfo.setLimitIndex(pageResult.offset());
        return pageInfo;
    }

    @Override
    public void addTransshipment(TransshipmentAddDTO addDTO) {
        System.out.println("addDTO = " + addDTO);
        // 校验调货数量
        if (addDTO.getTransNum() > addDTO.getProductInvent()) {
            throw new RuntimeException("调货数量不能大于库存数量！");
        }

        // 查找或创建目标商品
        Integer targetProductId = getOrCreateTargetProduct(addDTO);


        // 创建调货单
        Transshipment transshipment = new Transshipment();
        transshipment.setSourceStoreId(addDTO.getSourceStoreId());
        transshipment.setSourceProductId(addDTO.getSourceProductId());
        transshipment.setTargetStoreId(addDTO.getTargetStoreId());
//        transshipment.setTargetProductId(targetProduct.getProductId());
        transshipment.setTargetProductId(targetProductId);
        transshipment.setTransNum(addDTO.getTransNum());
        transshipment.setAuditState("0"); // 初始状态为未审核
        transshipment.setCreateBy(CurrentUtil.getId()); // 应该从登录用户中获取
        transshipment.setCreateTime(new Date());

        this.save(transshipment);

    }

    @Override
    public void confirmTransshipment(TransshipmentConfirmDTO confirmDTO) {
        Product sourceProduct = productMapper.selectById(confirmDTO.getSourceProductId());
        if (sourceProduct.getProductInvent() < confirmDTO.getTransNum()) {
            throw new RuntimeException("商品库存不足");
        }
        sourceProduct.setProductInvent(sourceProduct.getProductInvent() - confirmDTO.getTransNum());
        sourceProduct.setUpdateTime(new Date());
        productMapper.updateById(sourceProduct);

        Product targetProduct = productMapper.selectById(confirmDTO.getTargetProductId());
        // 如果目标商品不存在，则创建新商品
        if (targetProduct == null) {
            throw new RuntimeException("目标商品不存在");
        }
        targetProduct.setProductInvent(targetProduct.getProductInvent() + confirmDTO.getTransNum());
        targetProduct.setUpdateTime(new Date());
        productMapper.updateById(targetProduct);

        Transshipment transshipment = this.baseMapper.selectById(confirmDTO.getTransId());
        transshipment.setAuditState("1");
        this.baseMapper.updateById(transshipment);


    }

    private Integer getOrCreateTargetProduct(TransshipmentAddDTO addDTO) {
        // 根据商品编号查找目标商品
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Product::getProductNum, addDTO.getTargetProductNum());
        wrapper.eq(Product::getStoreId, addDTO.getTargetStoreId());
        Product targetProduct = productMapper.selectOne(wrapper);

        if (targetProduct != null) {
            return targetProduct.getProductId();
        }

        System.out.println("addDTO = " + addDTO);
        // 如果目标商品不存在，则复制源商品信息创建新商品
        Product sourceProduct = productMapper.selectById(addDTO.getSourceProductId());
        if (sourceProduct == null) {
            throw new RuntimeException("源商品不存在");
        }
        System.out.println("sourceProduct = " + sourceProduct);
        Product newProduct = new Product();
        BeanUtils.copyProperties(sourceProduct, newProduct);
        newProduct.setProductId(null); // 清空ID，让数据库自动生成
        newProduct.setProductNum(addDTO.getTargetProductNum());
        newProduct.setProductInvent(0); // 初始库存为0
        newProduct.setStoreId(addDTO.getTargetStoreId());
        newProduct.setCreateTime(new Date());
        newProduct.setUpdateTime(new Date());

        productMapper.insert(newProduct);
        return newProduct.getProductId();
    }
}




